import utils from '@/utils/utils'
import Layout from '@/layout'
import Nest2 from '@/layout/Nest2.vue'
import router from '@/router'

function rebuildTree(data) {
  const result = [] // 存放结果集
  const itemMap = {} //
  for (const item of data) {
    const id = item.id
    const pid = item.pid

    if (!itemMap[id]) {
      itemMap[id] = {
        children: []
      }
    }

    itemMap[id] = {
      ...item,
      children: itemMap[id]['children']
    }

    const treeItem = itemMap[id]

    if (pid === 0) {
      result.push(treeItem)
    } else {
      if (!itemMap[pid]) {
        itemMap[pid] = {
          children: []
        }
      }
      itemMap[pid].children.push(treeItem)
    }
  }
  return result
}

function getRouteDeep(menu, deep, addRoute) {
  //判断obj.children的长度是否大于0，大于0则deep+1，否则返回0
  if (menu.children.length) {
    deep++
    menu.children.forEach(item => {
      getRouteDeep(item, deep)
    })
  }
  //包含layout和Nest2的层级
  return deep + 2
}
//生成路由
/**
 *
 * @param {*} obj 路由对象
 * @param {*} index 当前路由深度
 * @param {*} deep 总路由深度
 */
function generateRoute(menu, obj, index, deep, path) {
  obj.path = index === 1 ? '/' :''
  // // / 重定向到home
  // if (menu.menuKey === 'home') {
  //   obj.redirect = '/home'
  // }

  if (index === 1) {
    obj.component = Layout
    // obj.path = '/'
    if(menu.children.length){
      obj.path += menu.menuKey
    }
  }
  if (index === 2) {
    obj.component = Nest2
    // obj.path = ''
  }
  // //其他层级
  if (index === 3) {
    obj.component = () => import(`@/${menu.path}.vue`)
    obj.path += menu.menuKey
    obj.name = menu.menuKey
  }
  //路由小于deep时，要生成children
  if (index < deep) {
    obj.children = []
    //children多个
    if (menu.children.length > 0) {
      for (let v of menu.children) {
        const objSub = {}
        obj.children.push(generateRoute(v, objSub, index + 1, deep, obj.path ))
      }
    } else {
      const objCur = {}
      obj.children.push(generateRoute(menu, objCur, index + 1, deep, obj.path))
    }
  }
  return obj
}

export const routes = []
const Types = {
  SET_MENU: 'SET_MENU',
  SET_ROUTES: 'SET_ROUTES'
}
// const rm = new RouteMenu()

const menu = {
  state: {
    activeMenuInfo: { activeMenuObj: {}, menuList: [] },
    menus: [],
    routes: []
  },
  actions: {
    getMenu({ commit }, menus) {
      return new Promise(async (resolve, rejct) => {
        let menus = [
          {
            id: 4,
            menuName: '首页',
            path: 'views/HomeView/index',
            sort: 1,
            label: '首页',
            hidden: 0,
            menuKey: 'home',
            parentIds: '5',
            icon: 'el-icon-s-order',
            children: null,
            pid: 0
          },
          {
            id: 5,
            menuName: 'TableLayout',
            path: 'views/TableLayout/index',
            sort: 1,
            label: 'TableLayout',
            hidden: 0,
            menuKey: 'tableLayout',
            parentIds: '5',
            icon: 'el-icon-s-order',
            children: null,
            pid: 0
          },
          {
            id: 6,
            menuName: '测试菜单',
            path: 'views/Test/index',
            sort: 1,
            label: '测试菜单',
            hidden: 0,
            menuKey: 'test',
            parentIds: '5',
            icon: 'el-icon-s-order',
            children: null,
            pid: 0
          },
          {
            id: 8,
            menuName: '测试菜单',
            path: 'views/Test/index',
            sort: 1,
            label: '测试菜单',
            hidden: 0,
            menuKey: 'test',
            parentIds: '6',
            icon: 'el-icon-s-order',
            children: null,
            pid: 6
          },
          {
            id: 7,
            menuName: '子菜单',
            path: 'views/Test/Child/index',
            sort: 1,
            label: '子菜单',
            hidden: 0,
            menuKey: 'child',
            parentIds: '6',
            icon: 'el-icon-s-order',
            children: null,
            pid: 6
          }
        ]

        menus = rebuildTree(menus)
        console.log('menus', menus)
        menus.forEach(menu => {
          //获取路由深度
          let deep = getRouteDeep(menu, 1, true)
          //路由对象
          let obj = {}
          generateRoute(menu, obj, 1, deep, '')
          console.log(obj);
          router.addRoute(obj)
        })
        
        //生成路由
        // const route = generateRoute(menus)
        commit('SET_MENU', menus)
        // commit('SET_ROUTES', route)
        resolve(menus)

        // commit('SET_MENU', menus);
        // resolve(menus);
      })
    }
  },
  mutations: {
    //设置菜单
    [Types.SET_MENU]: (state, data) => {
      state.menus = data
    },
    //设置路由
    [Types.SET_ROUTES]: (state, data) => {
      state.routes = data
    }
  }
}
export default menu
